package org.free.data;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

public class Person {

	String username;
	String password;
	int status;
	
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public static Key getPerson(String name, String password) {
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();

		Query q = new Query("Person");
		q.addFilter("name", Query.FilterOperator.EQUAL, name);
		q.addFilter("password", Query.FilterOperator.EQUAL, password);
		PreparedQuery pq = datastore.prepare(q);
		for (Entity result : pq.asIterable()) {
			return result.getKey();
		}
		return null;

	}

	public static Person getPerson(Key person) {
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();
		Entity personDtl = null;
		try {
			personDtl = datastore.get(person);
		} catch (EntityNotFoundException e) {
				
			e.printStackTrace();
			return null;
		}
		String username = (String) personDtl.getProperty("name");
		String password = (String) personDtl.getProperty("password");
		Person p = new Person();
		p.setPassword(password);
		p.setUsername(username);
		return p;

	}

	public static Key setPerson(String name, String password) {
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();

		Query q = new Query("Person");
		q.addFilter("name", Query.FilterOperator.EQUAL, name);
		q.addFilter("password", Query.FilterOperator.EQUAL, password);
		PreparedQuery pq = datastore.prepare(q);
		for (Entity result : pq.asIterable()) {
			return result.getKey();
		}

		Entity person = new Entity("Person");
		person.setProperty("name", name);
		person.setProperty("password", password);
		return datastore.put(person);

	}
}
